<template>
  <div class="items-center column">
    <div class="justify-between row" style="width: 100%">
      <q-btn color="negative" @click="handleClear">
        {{ $t("Clear") + $t("All") }}
      </q-btn>
      <q-btn color="negative" @click="handleAll">
        {{ $t("Select") + $t("All") }}
      </q-btn>
      <q-btn color="primary" @click="handleRoleMenu">
        {{ $t("Save") }}
      </q-btn>
    </div>
    <q-card-section style="width: 100%; max-height: 70vh" class="scroll">
      <q-tree
        dense
        style="width: 100%"
        :nodes="menuTree"
        node-key="menu_code"
        label-key="menu_code"
        selected-color="primary"
        v-if="menuTree.length !== 0"
        tick-strategy="leaf"
        v-model:ticked="ticked"
        v-model:expanded="expandedKeys"
      >
        <template v-slot:default-header="prop">
          <div class="items-center row">
            <q-icon
              :name="prop.node.icon || 'share'"
              size="28px"
              class="q-mr-sm"
            />
            <div :class="ifLeaf(prop.node)">{{ prop.node.title }}</div>
          </div>
        </template>
      </q-tree>
      <!-- <div>{{ ticked }}</div> -->
    </q-card-section>
    <q-inner-loading :showing="loading">
      <q-spinner-gears size="50px" color="primary" />
    </q-inner-loading>
  </div>
</template>

<script setup>
import useTableData from "src/composables/useTableData";
import { useQuasar } from "quasar";
import { postAction } from "src/utils/requestAction";
import { computed, onMounted, ref, toRefs } from "vue";
import { useI18n } from "vue-i18n";
import { ArrayToTree } from "src/utils/arrayAndTree";
import { usePermissionStore } from "src/stores/permission";
import { useRouter } from "vue-router";

const $q = useQuasar();
const { t } = useI18n();
const router = useRouter();
const permissionStore = usePermissionStore();
const url = {
  list: "menu/get-menu-list",
  roleMenuList: "role/get-role-menu-list",
  roleMenuEdit: "role/edit-role-menu",
};

const props = defineProps({
  row: {
    type: Object,
    required: true,
  },
});
const { row } = toRefs(props);

const { pagination, loading, tableData, getTableData } = useTableData(url);

const menuTree = computed(() => {
  if (tableData.value.length !== 0) {
    return ArrayToTree(tableData.value, "menu_code", "parent_code");
  }
  return [];
});

onMounted(async () => {
  pagination.value.rowsPerPage = 99999;
  await getTableData();
  await getRoleMenuList();
  console.log(tableData.value);
});

const ticked = ref([]);
const expandedKeys = ref([]);
const getRoleMenuList = () => {
  // 每次获取前，清空ticked
  ticked.value = [];
  postAction(url.roleMenuList, {
    role_code: row.value.role_code,
  }).then((res) => {
    if (res.code === 1) {
      res.data.records.forEach((item) => {
        // 将有权限的菜单勾选上
        ticked.value.push(item.menu_code);
        // 除了系统管理以外的菜单自动展开
        if (item.menu_code !== "log" && item.menu_code !== "system") {
          expandedKeys.value.push(item.menu_code);
        }
      });
    }
  });
};

const handleRoleMenu = () => {
  const menuCode = [];
  for (let i of ticked.value) {
    menuCode.push(i);
    let parent_menu = tableData.value.find((item) => item.menu_code === i);
    while (parent_menu && parent_menu.parent_code) {
      // 如果不存在在menuCode里添加
      if (!menuCode.includes(parent_menu.parent_code)) {
        menuCode.push(parent_menu.parent_code);
      }
      parent_menu = tableData.value.find(
        (item) => item.menu_code === parent_menu.parent_code
      );
    }
  }
  console.log(menuCode);
  postAction(url.roleMenuEdit, {
    role_code: row.value.role_code,
    menu_code: menuCode,
  }).then((res) => {
    if (res.code === 1) {
      $q.notify({
        type: "positive",
        message: res.message,
      });
      getRoleMenuList();

      permissionStore.GetUserMenu().then((res) => {
        //正常返回了
        if (res) {
          $q.notify({
            type: "positive",
            message: "成功刷新用户权限!",
          });
        }
      });
    }
  });
};
const handleClear = () => {
  ticked.value = [];
};
const handleAll = () => {
  tableData.value.forEach((item) => {
    ticked.value.push(item.menu_code);
  });
};

const ifLeaf = (node) => {
  if (node.children.length === 0) {
    return "";
  }
  return "text-weight-bold";
};
</script>

<script>
import { defineComponent } from "vue";

export default defineComponent({
  name: "RolePermissionMenu",
});
</script>
